package com.gxa.modules.pay.controller;


import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.gxa.common.utils.Result;
import com.gxa.modules.pay.config.AliPayProperties;
import com.gxa.modules.pay.service.PayService;
import com.gxa.modules.sys.entity.Combo;
import com.gxa.modules.sys.entity.PayOrder;
import com.gxa.modules.sys.service.ComboService;
import com.ijpay.alipay.AliPayApiConfig;
import com.ijpay.alipay.AliPayApiConfigKit;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


@Api(tags = "支付宝回调接口")
@RestController
@RequestMapping("/pay/alipay")
@Slf4j
public class ReturnController extends AbstractAliPayApiController{

    @Autowired
    private AliPayProperties properties;

    @Autowired
    private PayService payService;


    @Override
    public AliPayApiConfig getApiConfig() throws AlipayApiException {
        AliPayApiConfig aliPayApiConfig;
        try {
            aliPayApiConfig = AliPayApiConfigKit.getApiConfig(properties.getAppId());
        } catch (Exception e) {
            aliPayApiConfig = AliPayApiConfig.builder()
                    .setAppId(properties.getAppId())
                    .setAliPayPublicKey(properties.getPublicKey())
//                .setAppCertPath(properties.getAppCertPath())
//                .setAliPayCertPath(properties.getAliPayCertPath())
//                .setAliPayRootCertPath(properties.getAliPayRootCertPath())
                    .setCharset("UTF-8")
                    .setPrivateKey(properties.getPrivateKey())
                    .setServiceUrl(properties.getServerUrl())
                    .setSignType("RSA2")
                    // 普通公钥方式
                    .build();
            // 证书模式
//                .buildByCert();
        }
        return aliPayApiConfig;
    }


    @RequestMapping("/return")
    public Result back(@RequestParam Map<String, Object> params){

        log.info("支付通知,正在执行,通知参数:{}", JSON.toJSONString(params));

        try {
            this.payService.updateState(params);

            return new Result().ok();
        }catch (Exception e){
           e.printStackTrace();
           return new Result().error();
        }

    }

}
